<template>
  <div class="app-container">
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />

    <!-- 表格：展示excel的内容 -->
    <el-table
      :data="tableData"
      border
      highlight-current-row
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column
        v-for="item of tableHeader"
        :key="item"
        :prop="item"
        :label="item"
      />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    async doImport(data) {
      try {
        const res = await importEmployee(data)
        console.log('importEmployee', res)
        this.$message.success('导入成功')

        // 页面后退
        this.$router.push('/employees')
      } catch (err) {
        console.log('importEmployee', err)
        this.$message.error('导入失败')
      }
    },
    //  1. 把数据从excel文件读入到浏览器内存
    handleSuccess({ results, header }) {
      console.log(header, results)
      this.tableData = results
      this.tableHeader = header
      // 2. 按接口要求 组装数据
      const data = this.tranExcel(results)
      console.log('按接口要求 组装数据', data)
      // 3. 调用接口做上传
      this.doImport(data)
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    tranExcel(results) {
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      return results.map((zhObj) => {
        const enObj = {}
        const zhKeys = Object.keys(zhObj) // ['姓名', '手机号']

        zhKeys.forEach((zhKey) => {
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            // 后端需要的日期格式是标准时间
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
        })

        return enObj
      })
    }
  }
}
</script>
